package com.fc.mall.portal.service.impl;

import com.fc.mall.mapper.*;
import com.fc.mall.model.*;
import com.fc.mall.mapper.UmsMemberInviteHistoryMapper;
import com.fc.mall.mapper.UmsMemberLevelMapper;
import com.fc.mall.mapper.UmsMemberMapper;
import com.fc.mall.mapper.UmsMemberUpgradeMapper;
import com.fc.mall.portal.dao.PortalOrderDao;
import com.fc.mall.portal.domain.OmsOrderDetail;
import com.fc.mall.portal.dto.OmsOrderStatistics;
import com.fc.mall.portal.service.UmsMemberService;
import com.fc.mall.portal.service.UmsMemberUpgradeService;
import com.fc.mall.util.Constants;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UmsMemberUpgradeServiceImpl implements UmsMemberUpgradeService {
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private UmsMemberInviteHistoryMapper memberInviteHistoryMapper;
    @Autowired
    private UmsMemberUpgradeMapper memberUpgradeMapper;

    @Autowired
    private PortalOrderDao orderDao;

    @Autowired
    private UmsMemberService memberService;


    @Override
    public UmsMemberUpgrade getMemberUpgradeByMemberId(Long memberId) {
        UmsMemberUpgrade memberUpgrade = null;

        UmsMemberUpgradeExample example = new UmsMemberUpgradeExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        List<UmsMemberUpgrade> memberUpgradeList = memberUpgradeMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberUpgradeList))
        {
            memberUpgrade = memberUpgradeList.get(0);
        }
        return memberUpgrade;
    }

    @Override
    public void initMemberUpgrade(UmsMember umsMember)
    {
        UmsMemberUpgrade memberUpgrade = new UmsMemberUpgrade();
        memberUpgrade.setMemberId(umsMember.getId());
        memberUpgrade.setCurrentLevelId(umsMember.getMemberLevelId());
        memberUpgrade.setChildCount(0);
        memberUpgrade.setCommissionAmount(BigDecimal.valueOf(0));
        memberUpgradeMapper.insert(memberUpgrade);
    }

    @Override
    public void handleInviteMember(Long parentMemberId, Long childMemberId)
    {
        if(parentMemberId == null || childMemberId == null)
        {
            return;
        }
        UmsMember parentMember = memberMapper.selectByPrimaryKey(parentMemberId);
        if(parentMember == null)
        {
            return;
        }

        // 1. 拉新人列表添加记录
        UmsMemberInviteHistory inviteHistory = new UmsMemberInviteHistory();
        inviteHistory.setMemberId(parentMember.getId());
        inviteHistory.setMemberLevelId(parentMember.getMemberLevelId());
        inviteHistory.setChildMemberId(childMemberId);
        // 默认为未激活拉新人记录
        inviteHistory.setEffective(Constants.Status.Inactive.getValue());
        inviteHistory.setInviteTime(new Date());
        memberInviteHistoryMapper.insert(inviteHistory);

        updateMemberUpgradeCondition(parentMember.getId(), Constants.UpgradeOperation.Invite);
    }

    @Override
    public void handleTradeUpgrade(Long memberId, Long orderId) {

        OmsOrderDetail orderDetail = orderDao.getDetail(orderId);
        List<OmsOrderItem> orderItemList = orderDetail.getOrderItemList();
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria();
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        boolean isSpecialUpgrade = false;
        for(OmsOrderItem item : orderItemList)
        {
            List<UmsMemberLevel> upgradeLevelList = memberLevelList.stream()
                    .filter(v -> Constants.Status.Active.getValue() == v.getActive().intValue()
                            && null != v.getProductId()
                            && v.getProductId().equals(item.getProductId()))
                    .collect(Collectors.toList());
            if(!upgradeLevelList.isEmpty())
            {
                memberSpecialUpgrade(memberId, upgradeLevelList);
                isSpecialUpgrade = true;
            }
        }
        if(!isSpecialUpgrade)
        {
            updateMemberUpgradeCondition(memberId, Constants.UpgradeOperation.Trade);
        }

    }

    private void memberSpecialUpgrade(Long memberId, List<UmsMemberLevel> memberLevelList)
    {
        UmsMember currentMember = memberService.getCurrentMember();
        UmsMemberUpgrade memberUpgrade = getMemberUpgradeByMemberId(memberId);
        memberLevelList.stream().forEach(level -> {
            if(level.getId() > currentMember.getMemberLevelId())
            {
                // 达到了升级条件
                // 1. 升级会员的级别
                currentMember.setLevelType(level.getLevelType());
                currentMember.setMemberLevelId(level.getId());
                memberMapper.updateByPrimaryKeySelective(currentMember);

                // 2. 重置会员的本level的升级条件状态
                memberUpgrade.setCurrentLevelId(level.getId());
                memberUpgrade.setExpiredType(3);
                Integer expiredDate = null;
                try {
                    expiredDate = DateTimeHelper.getEpochTimeFromString("2020-11-20 00:00:00");
                } catch (ParseException e) {
                }
                memberUpgrade.setExpiredDate(expiredDate);
                memberUpgradeMapper.updateByPrimaryKeySelective(memberUpgrade);
            }
        });

    }

    /**
     * 更新用户的升级当前条件
     * @param memberId
     */
    @Override
    public void updateMemberUpgradeCondition(Long memberId, Constants.UpgradeOperation upgradeOperation)
    {
        OmsOrderStatistics orderStatistics = orderDao.getOrderStatistics(memberId, Constants.OrderStatus.HAS_RECEIVE.getValue());
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andParentMemberIdEqualTo(memberId).andLockStatusEqualTo(Constants.MemberLockStatus.Lock.getValue());
        Integer increaseChildCount = memberMapper.countByExample(example);
        BigDecimal paymentMoney = null == orderStatistics.getTotalAmount() ? BigDecimal.ZERO : orderStatistics.getTotalAmount();
        Integer totalOrderCount = orderStatistics.getTotalCount().intValue();
        // 2. 更新用户当前level的升级条件
        UmsMemberUpgrade memberUpgrade = getMemberUpgradeByMemberId(memberId);
        if(memberUpgrade == null)
        {
            return;
        }

        // 邀请粉丝数量
        memberUpgrade.setChildCount(increaseChildCount);
        // 自购订单已收货金额
        memberUpgrade.setCommissionAmount(paymentMoney);
        // 自购订单已收货数量
        memberUpgrade.setTotalOrderCount(totalOrderCount);

        // 核对并处理用户升级
        checkHandleMemberLevelToUpgrade(memberUpgrade, upgradeOperation);

        // 更新当前用户的升级状态, 拉新人数 或 分佣金额
        memberUpgradeMapper.updateByPrimaryKey(memberUpgrade);
    }

    /**
     * 核对并处理用户升级
     * @param memberUpgrade
     * @return
     */
    private UmsMemberUpgrade checkHandleMemberLevelToUpgrade(UmsMemberUpgrade memberUpgrade, Constants.UpgradeOperation upgradeOperation)
    {
        // 1. 获取会员升级条件
        UmsMemberLevel umsMemberLevel = memberLevelMapper.selectByPrimaryKey(memberUpgrade.getCurrentLevelId());
        List<UmsMemberLevel> activeLevelList = getActiveMemberLevelList();
        List<UmsMemberLevel> canUpdateLevelList = activeLevelList.stream().filter(v -> v.getId().compareTo(umsMemberLevel.getId()) == 1).collect(Collectors.toList());
        if(canUpdateLevelList.isEmpty())
        {
            return memberUpgrade;
        }
        if(null ==umsMemberLevel)
        {
            return memberUpgrade;
        }
        UmsMemberLevel nextMemberLevel = canUpdateLevelList.get(0);
        if(isUpgrade(nextMemberLevel, memberUpgrade, upgradeOperation))
        {
            // 达到了升级条件
            // 1. 升级会员的级别
            UmsMember currentMember = memberService.getCurrentMember();
            currentMember.setMemberLevelId(nextMemberLevel.getId());
            currentMember.setLevelType(nextMemberLevel.getLevelType());
            memberMapper.updateByPrimaryKeySelective(currentMember);
            // 2. 重置会员的本level的升级条件状态
            memberUpgrade.setCurrentLevelId(nextMemberLevel.getId());
        }
        return memberUpgrade;
    }



    private List<UmsMemberLevel> getActiveMemberLevelList()
    {
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria();
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        return memberLevelList.stream().filter(v -> Constants.Status.Active.getValue() == v.getCommissionStatus().intValue()).collect(Collectors.toList());
    }

    /**
     * 是否达到了升级的条件
     * @param umsMemberLevel
     * @param memberUpgrade
     * @return
     */
    private boolean isUpgrade(UmsMemberLevel umsMemberLevel, UmsMemberUpgrade memberUpgrade, Constants.UpgradeOperation upgradeOperation)
    {
        if(upgradeOperation.getValue() == Constants.UpgradeOperation.SpecialTrad.getValue())
        {
            return true;
        }
        else
        {
            if(Constants.UpgradeCondition.And.getValue().equals(umsMemberLevel.getUpgradeCondition()))
            {
                return memberUpgrade.getChildCount().compareTo(umsMemberLevel.getInviteNumber()) > -1
                        && memberUpgrade.getCommissionAmount().compareTo(umsMemberLevel.getSelfPurchaseAmount()) > -1
                        && memberUpgrade.getTotalOrderCount().compareTo(umsMemberLevel.getSelfPurchaseNum()) > -1;
            }
            else if (Constants.UpgradeCondition.Or.getValue().equals(umsMemberLevel.getUpgradeCondition()))
            {
                return memberUpgrade.getChildCount().compareTo(umsMemberLevel.getInviteNumber()) > -1
                        || memberUpgrade.getCommissionAmount().compareTo(umsMemberLevel.getSelfPurchaseAmount()) > -1
                        || memberUpgrade.getTotalOrderCount().compareTo(umsMemberLevel.getSelfPurchaseNum()) > -1;
            }
        }
        return false;
    }
}
